package com.apes.framework.plugin.soe.metadata;

import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;

/**
 * 功能：条件因子
 *
 * @author xul
 * @create 2018-09-21 13:25
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SceneFlowFactor.CONST_TABLE_NAME)
public class SceneFlowFactor extends BaseModel {
    public static final String CONST_TABLE_NAME = "soe_scene_flow_factor";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "条件因子")
    @Comment("编码")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_attr_id", nullable = false, referencedColumnName = "id")
    @Comment("操作数（字段名称）")
    private BusinessAttribute attribute;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "operate_id", nullable = false, referencedColumnName = "id")
    @Comment("操作")
    private Operate operate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_attr_value_id", nullable = false, referencedColumnName = "id")
    @Comment("操作值")
    private BusinessAttributeValue value;

    @ManyToOne(optional = false)
    @JoinColumn(name = "scene_flow_id", referencedColumnName = "id", nullable = false)
    @Comment("场景编排（场景流）")
    private SceneFlow sceneFlow;

    public String buildScript() {
        StringBuffer sb = new StringBuffer();
        // 处理boolean类型被解析为'true'的问题
        if(value.getCode().equals("true") || value.getCode().equals("false")){
            sb.append(attribute.getCode()).append(" ").append(operate.getId()).append(" ").append(value.getCode().trim());
        } else {
            sb.append(attribute.getCode()).append(" ").append(operate.getId()).append(" '").append(value.getCode().trim()).append("'");
        }
        return sb.toString();
    }
}
